import { editBlogConfigApi, getBlogApi } from '@/api/cms/blog/blog'
import { BlogModel } from '@/api/cms/blog/BlogModel'
import useInstance from '@/hooks/useInstance'
import { ElForm } from 'element-plus'
import { Result, StatusCode } from '@/http/request'
import type { UploadProps } from 'element-plus'
import { onMounted, ref, reactive, onBeforeMount } from 'vue'
import { getToken } from '@/utils/auth'
import { getUploadUrlApi } from '@/api/cms/blog/blog'

export default function useBlog(blogModel: BlogModel) {
    const { global } = useInstance()
    const uploadUrl = ref('')
    const favicon = ref<string>('')
    const logo = ref<string>('')
    const darkLogo = ref<string>('')
    const headerObj = { Authorization: 'Bearer ' + getToken() }
    // 表单ref属性
    const blogForm = ref<InstanceType<typeof ElForm>>()

    const getBlogConfig = async () => {
        let res = await getBlogApi()
        if (res && res.code == StatusCode.Success) {
            // 清空表单
            global.$resetForm(blogForm.value, blogModel)
            // 把要编辑的数据，放到表单绑定的model里面
            const data = reactive<BlogModel>({
                baseURL: res.data.baseURL,
                title: res.data.title,
                theme: res.data.theme,
                DefaultContentLanguage: res.data.DefaultContentLanguage,
                paginate: res.data.paginate,
                limit: res.data.limit,
                author: res.data.params.author,
                favicon: res.data.params.favicon,
                logo: res.data.params.logo,
                darkLogo: res.data.params.darkLogo,
                description: res.data.params.description,
                dateFormat: res.data.params.dateFormat,
                blogGroupBy: res.data.params.blogGroupBy,
                latestPostsCount: res.data.params.latestPostsCount,
                showAllPostsOnHomePage: res.data.params.showAllPostsOnHomePage
                    ? 1
                    : 0,
                article_toc: res.data.params.article.toc ? 1 : 0,
                about_title: res.data.params.about.title,
                footer_since: res.data.params.footer.since,
                footer_customText: res.data.params.footer.customText
            })
            global.$objCoppy(data, blogModel)
        }
    }

    const paginateHandleChange = (value: number) => {
        blogModel.paginate = value
    }

    const limitHandleChange = (value: number) => {
        blogModel.limit = value
    }

    const latestPostsCountHandleChange = (value: number) => {
        blogModel.latestPostsCount = value
    }

    const footerSinceHandleChange = (value: number) => {
        blogModel.footer_since = value
    }

    const getUploadUrl = () => {
        uploadUrl.value = getUploadUrlApi()
    }

    const reset = () => {
        getBlogConfig()
    }

    const save = () => {
        blogForm.value?.validate(async (valid) => {
            if (valid) {
                let res: Result
                res = await editBlogConfigApi(blogModel)
                if (res && res.code == StatusCode.Success) {
                    getBlogConfig()
                    global.$message({
                        message: res.msg,
                        type: 'success'
                    })
                }
            }
        })
    }

    const handleFaviconSuccess: UploadProps['onSuccess'] = (
        res,
        uploadFile
    ) => {
        // console.log(uploadFile)
        if (res && res.code == StatusCode.Success) {
            favicon.value = URL.createObjectURL(uploadFile.raw!)
            blogModel.favicon = URL.createObjectURL(uploadFile.raw!)
            global.$message({
                message: '上传成功！',
                type: 'success'
            })
        } else {
            global.$message({
                message: res.msg,
                type: 'error'
            })
        }
    }

    const beforeFaviconUpload: UploadProps['beforeUpload'] = (rawFile) => {
        if (rawFile.type == 'image/x-icon') {
            if (rawFile.size / 1024 / 1024 > 1) {
                global.$message({
                    message: '图片大小不能超过1MB！',
                    type: 'error'
                })
                return false
            }
            return true
        } else {
            global.$message({
                message: '必须是PNG格式的图片！',
                type: 'error'
            })
            return false
        }
    }

    const handleLogoSuccess: UploadProps['onSuccess'] = (res, uploadFile) => {
        // console.log(uploadFile)
        if (res && res.code == StatusCode.Success) {
            logo.value = URL.createObjectURL(uploadFile.raw!)
            blogModel.logo = res.data
            global.$message({
                message: '上传成功！',
                type: 'success'
            })
        } else {
            global.$message({
                message: res.msg,
                type: 'error'
            })
        }
    }

    const beforeLogoUpload: UploadProps['beforeUpload'] = (rawFile) => {
        if (rawFile.type == 'image/png') {
            if (rawFile.size / 1024 / 1024 > 1) {
                global.$message({
                    message: '图片大小不能超过1MB！',
                    type: 'error'
                })
                return false
            }
            return true
        } else {
            global.$message({
                message: '必须是PNG格式的图片！',
                type: 'error'
            })
            return false
        }
    }

    const handleDarkLogoSuccess: UploadProps['onSuccess'] = (
        res,
        uploadFile
    ) => {
        // console.log(uploadFile)
        if (res && res.code == StatusCode.Success) {
            darkLogo.value = URL.createObjectURL(uploadFile.raw!)
            blogModel.darkLogo = res.data
            global.$message({
                message: '上传成功！',
                type: 'success'
            })
        } else {
            global.$message({
                message: res.msg,
                type: 'error'
            })
        }
    }

    const beforeDarkLogoUpload: UploadProps['beforeUpload'] = (rawFile) => {
        if (rawFile.type == 'image/png') {
            if (rawFile.size / 1024 / 1024 > 1) {
                global.$message({
                    message: '图片大小不能超过1MB！',
                    type: 'error'
                })
                return false
            }
            return true
        } else {
            global.$message({
                message: '必须是PNG格式的图片！',
                type: 'error'
            })
            return false
        }
    }

    onBeforeMount(async () => {
        await getUploadUrl()
    })

    onMounted(() => {
        getBlogConfig()
    })

    return {
        blogForm,
        uploadUrl,
        headerObj,
        paginateHandleChange,
        limitHandleChange,
        latestPostsCountHandleChange,
        footerSinceHandleChange,
        handleFaviconSuccess,
        beforeFaviconUpload,
        handleLogoSuccess,
        beforeLogoUpload,
        handleDarkLogoSuccess,
        beforeDarkLogoUpload,
        reset,
        save,
        favicon,
        logo,
        darkLogo
    }
}
